package com.wfs.suanfa.nio.demo.echo.nonio;

import lombok.SneakyThrows;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class PlainOioServer {
    @SneakyThrows
    public static void server(int port){
        ServerSocket socket=new ServerSocket(port);
        for (;;){
            //接受连接
            Socket clientSocket=socket.accept();
            System.out.println("Accepted connection from "+clientSocket);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OutputStream out= null;
                    try {
                        out = clientSocket.getOutputStream();
                        out.write("Hi\r\n".getBytes(StandardCharsets.UTF_8));
                        out.flush();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }).start();
        }
    }

    public static void main(String[] args) {
        server(7001);
    }
}
